#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t mtx;
pthread_cond_t cond;

void* ctrl(void* args)
{
    string name=(char*)args;
    while(true)
    {
        cout<<"master say:begin work"<<endl;
        pthread_cond_signal(&cond);//唤醒条件变量下等待的一个线程
        sleep(3);
    }
}

void* work(void* args)
{
    int number=*(int *)args;
    delete (int*)args;
    while(true)
    {
        pthread_cond_wait(&cond,&mtx);
        cout<<"worker:"<<number<<"is working"<<endl;
    }
}
int main()
{
    pthread_mutex_init(&mtx,nullptr);
    pthread_cond_init(&cond,nullptr);

    pthread_t master;
    pthread_t worker[3];

    //主线程
    pthread_create(&master,nullptr,ctrl,(void*)"boss");

    //创建3个work线程
    for(int i=0;i<3;i++)
    {
        int *number=new int (i);
        pthread_create(worker+i,nullptr,work,(void*)number);
    }
    for(int i=0;i<3;i++){
        pthread_join(worker[i],nullptr);
    }
    pthread_join(master,nullptr);

    pthread_mutex_destroy(&mtx);
    pthread_cond_destroy(&cond);


}